package com.sskj.app.config.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.fegin.bean.app.StockUser;
import com.fegin.client.app.StockUserFegin;
import com.sskj.app.util.cacheUtil.JedisUtil;
import com.util.Respons.ResponseUtil;
import com.util.auth.AuthSign;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.List;

/**
 * Created by Zhang on 2018/8/26.
 */
@Configuration
public class Appinterceptor implements HandlerInterceptor {
    @Autowired
    JedisUtil jedisUtil;
    @Autowired
    StockUserFegin stockUserFegin;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        //校验token
        if (AuthSign.verify(token)) {
            //判断用户是否可用    redis   key-value   token是key
            List<StockUser> stockUsers = jedisUtil.getList(token);
            if (stockUsers != null) {
                if (stockUsers.get(0).getIsDisable() == 1) {
                    response.setCharacterEncoding("UTF-8");
                    response.setContentType("application/json");
                    response.setStatus(401);
                    PrintWriter printWriter = response.getWriter();
                    printWriter.print(JSONObject.toJSONString(ResponseUtil.getDisableResponseMap()));
                    printWriter.flush();
                    printWriter.close();
                    return false;
                }
            }
            return true;
        } else {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json");
            response.setStatus(401);
            PrintWriter printWriter = response.getWriter();
            printWriter.print(JSONObject.toJSONString(ResponseUtil.getTokenErrResponseMap()));
            printWriter.flush();
            printWriter.close();
            return false;
        }

    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
